<template>
  <div>
    <el-row>
      <el-col :span="12">
        <el-input
          size="small"
          class="m-r-10"
          style="width: 300px"
          placeholder="请输入关键字"
          v-model="search.queryStr"
          clearable
          @change="query"
        />
      </el-col>
      <el-col :span="12" class="flex-end">
        <select-add-filling-machine-button
          @select="handleFillingMachineSelected"
          button-name="添加加注机"
        />
      </el-col>
    </el-row>
    <el-table
      class="my-table m-t-20"
      :data="data"
      v-loading="loading"
      style="width: 100%"
      border
      :header-cell-style="{ background: '#eee', color: '#000' }"
    >
      <el-table-column type="index" align="center" label="序号" width="60" />
      <el-table-column prop="macCode" label="加注机编号" min-width="120" />
      <el-table-column prop="siteName" label="加注站名称" width="180" />
      <el-table-column fixed="right" label="操作" align="center" width="200">
        <template v-slot="scope">
          <el-dropdown @command="handleCommand">
            <div class="el-dropdown-link">
              操作列表<i class="el-icon-arrow-down el-icon--right"></i>
            </div>
            <el-dropdown-menu slot="dropdown">
              <auth-wrapper btn-key="filling-machine:edit-machine">
                <el-dropdown-item
                  icon="el-icon-plus"
                  :command="{ c: 'edit-machine', v: scope.row }"
                  >编辑</el-dropdown-item
                >
              </auth-wrapper>
              <auth-wrapper btn-key="filling-machine:view-qcode">
                <el-dropdown-item
                  icon="el-icon-document"
                  :command="{ c: 'view-qcode', v: scope.row }"
                  >二维码</el-dropdown-item
                >
              </auth-wrapper>
              <auth-wrapper btn-key="filling-team:remove-machine">
                <el-dropdown-item
                  icon="el-icon-s-operation"
                  :command="{ c: 'remove-machine', v: scope.row }"
                  >移除机器</el-dropdown-item
                >
              </auth-wrapper>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <app-pagination
      ref="paginationRef"
      :total="total"
      :page-size="page.size"
      class="m-t-20"
      @change="pageChange"
    />
    <div class="h-100px"></div>

    <el-dialog
      title="下载二维码"
      append-to-body
      :visible.sync="showQrImgFlag"
      width="600px"
    >
      <div class="flex-center">
        <div></div>
        <div id="qrCodeDiv" ref="qrCodeDiv" class="m-r-10"></div>
        <div></div>
      </div>
      <div class="flex-center">
        <div></div>
        <el-button type="text" @click="downloadQrImg">下载</el-button>
        <div></div>
      </div>
    </el-dialog>

    <el-dialog
      title="编辑自用加注机"
      append-to-body
      :visible.sync="showAddNewFlag"
      width="800px"
    >
      <el-form
        :model="formData"
        :rules="rules"
        ref="formRef"
        label-width="180px"
      >
        <el-form-item label="加注机编号" prop="macCode">
          <span v-html="formData.macCode"></span>
        </el-form-item>
        <el-form-item label="加注机名称" prop="deviceName">
          <span v-html="formData.deviceName"></span>
        </el-form-item>
        <el-form-item label="加注机名称" prop="siteName">
          <span v-html="formData.siteName"></span>
        </el-form-item>
        <el-form-item label="销售单价(元)" prop="ureaPrice">
          <span v-html="formData.ureaPrice"></span>
        </el-form-item>
        <el-form-item label="协议单价(元)" prop="teamMachinePrice">
          <el-input-number
            :min="0"
            class="w-40"
            v-model="formData.teamMachinePrice"
            size="small"
          />
        </el-form-item>
        <el-form-item label="独立机器" prop="teamIsSeal">
          <div>
            <el-radio v-model="formData.teamIsSeal" :label="0">否</el-radio>
            <el-radio v-model="formData.teamIsSeal" :label="1">是</el-radio>
          </div>
          <div>
            <span style="color: red"
              >注：独立机器不参与分润业务，且限制其他客户进行使用</span
            >
          </div>
        </el-form-item>
        <el-form-item label="二维码" prop="qrcodeType">
          <div>
            <el-radio v-model="formData.qrcodeType" :label="1"
              >启用独立二维码</el-radio
            >
            <el-radio v-model="formData.qrcodeType" :label="0"
              >使用设备原二维码</el-radio
            >
          </div>
        </el-form-item>
        <el-form-item class="m-t-30">
          <el-button @click="showAddNewFlag = false" icon="el-icon-close"
            >取消</el-button
          >
          <auth-wrapper btn-key="edit-filling-machine:save">
            <el-button
              type="primary"
              @click="editFillingMachine"
              :loading="saveLoading"
              icon="el-icon-check"
              >保存</el-button
            >
          </auth-wrapper>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import AppPagination from "@/components/business/app-pagination";
import SelectAddFillingMachineButton from "@/components/business/select-add-filling-machine-button";
import {
  getRecords,
  equals,
  msgSuccess,
  getRespData,
  getTotal,
  isListEmpty,
  isStringBlank,
  strEquals,
} from "@/util/common-util";
import {
  getPage,
  updateFillingMachine,
  detailById,
} from "@/api/business/filling-machine";
import QRCode from "qrcodejs2";

import {
  updateTeamFillMachine,
  unbindTeamFillMachine,
} from "@/api/business/filling-team";

export default {
  name: "contract-customer-detail-filling-machine-tab",
  components: { AppPagination, SelectAddFillingMachineButton },
  props: ["id"],
  data() {
    return {
      saveLoading: false,
      page: {
        size: 20,
        current: 1,
      },
      showImgFlag: false,
      qrLoading: false,
      showQrImgFlag: false,
      showAddNewFlag: false,
      total: 0,
      search: {
        // queryStr: "",
        teamId: "",
      },
      searchDate: "",
      showSearchFlag: true,
      loading: false,
      data: [],
      summaryDetail: {},
      currRow: {},
      selectMachines: [],
      formData: {
        id: "",
        macCode: "",
        deviceName: "",
        siteName: "",
        teamIsSeal: "",
      },
    };
  },
  created() {
    this.search.teamId = this.id;
    this.query();
  },
  filters: {
    teamIsSeal(v) {
      if (equals(v, 0)) return "否";
      if (equals(v, 1)) return "是";
      return "未知";
    },
    qrcodeType(v) {
      if (equals(v, 1)) return "独立二维码";
      if (equals(v, 0)) return "设备原二维码";
      return "";
    },
  },
  methods: {
    handleFillingMachineSelected(_selectList) {
      var fillingMachineIds = [];
      for (const item of _selectList) {
        fillingMachineIds.push(item.id);
      }
      var form = {
        id: this.id,
        teamName: "test",
        fillMachineIds: fillingMachineIds,
      };
      updateTeamFillMachine(form)
        .then((res) => {
          msgSuccess();
          this.query();
          this.saveLoading = false;
        })
        .catch(() => {
          this.saveLoading = false;
        });
    },
    query() {
      this.loading = true;
      getPage(this.page, this.search)
        .then((res) => {
          this.data = getRecords(res);
          this.total = getTotal(res);
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    pageChange(_page) {
      this.page = _page;
      this.query();
    },
    editFillingMachine() {
      this.$refs.formRef.validate((valid, errObj) => {
        if (valid) {
          this.saveLoading = true;
          updateFillingMachine(this.formData)
            .then((res) => {
              msgSuccess();
              this.saveLoading = false;
              this.showAddNewFlag = false;
            })
            .catch(() => {
              this.saveLoading = false;
              msgError(err);
            });
        }
      });
    },
    handleCommand(_command) {
      const row = _command.v;
      if (strEquals(_command.c, "edit-machine")) {
        this.showAddNewFlag = true;
        this.formData = row;
      }
      if (strEquals(_command.c, "view-qcode")) {
        this.showQrImgFlag = true;
        this.qrLoading = true;
        detailById(row.id)
          .then((res) => {
            var data = getRespData(res);
            var codeContent;
            if (data.qrcodeType == 0) {
              codeContent = data.macQrCode;
            }
            if (data.qrcodeType == 1) {
              codeContent = data.macCode;
            }
            this.buildQr(codeContent);
            this.qrLoading = false;
          })
          .catch((err) => {
            msgError(err);
            this.qrLoading = false;
          });
      }
      if (strEquals(_command.c, "remove-machine")) {
        var form = {
          id: row.teamId,
          teamName: "test",
          fillMachineIds: [row.id],
        };
        unbindTeamFillMachine(form)
          .then((res) => {
            msgSuccess();
            this.query();
            this.saveLoading = false;
          })
          .catch(() => {
            this.saveLoading = false;
          });
      }
    },
    buildQr(codeContent) {
      if (codeContent == null) {
        return;
      }
      if (this.qr != null) {
        this.qr.makeCode(codeContent);
      } else {
        setTimeout(() => {
          if (this.qr == null) {
            this.qr = new QRCode(this.$refs.qrCodeDiv, {
              text: codeContent,
              width: 300,
              height: 300,
              colorDark: "#333333", //二维码颜色
              colorLight: "#ffffff", //二维码背景色
              correctLevel: QRCode.CorrectLevel.L, //容错率，L/M/H
            });
          }
        }, 400);
      }
    },
    downloadQrImg() {
      let dom = document.getElementById("qrCodeDiv");
      // 获取dom二维码图片的连接
      let url = dom.childNodes[1].src; //codeIMG  要下载的路径
      let link = document.createElement("a");
      // 这里是将url转成blob地址，
      fetch(url)
        .then((res) => res.blob())
        .then((blob) => {
          // 将链接地址字符内容转变成blob地址
          link.href = URL.createObjectURL(blob);
          link.download = "二维码";
          document.body.appendChild(link);
          link.click();
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.my-table {
  ::v-deep .el-button--small {
    padding: 0 5px !important;
    font-size: 14px !important;
  }

  ::v-deep td {
    padding: 8px 0 !important;
  }
}
</style>
